
import  demo
from past.builtins import raw_input

import cv2

import tkinter.filedialog
import tkinter.messagebox #这个是消息框，对话框的关键
import os #获得 dir
#socket
import socket
import threading
import time
import sys
# end socket
import queue

# socket
def deal_data(sock, addr):
    print('Accept new connection from {0}'.format(addr))
    ########conn.send(('Hi, Welcome to the server!').encode())
    '''
    while 1:
        data = conn.recv(1024)
        print('{0} client send data is {1}'.format(addr,
                                                   data.decode()))  # b'\xe8\xbf\x99\xe6\xac\xa1\xe5\x8f\xaf\xe4\xbb\xa5\xe4\xba\x86'
        time.sleep(1)
        if data == 'exit' or not data:
            print('{0} connection close'.format(addr))
            conn.send(bytes('Connection closed!'), 'UTF-8')
            break
        conn.send(bytes('Hello, {0}'.format(data), "UTF-8"))  # TypeError: a bytes-like object is required, not 'str'
    '''
    x=True
    while x:
        print("start..bb....")

        total_data = b''
        num = 0
        data = sock.recv(1024)
        total_data += data
        num = len(data)
        print(num)
        # 如果没有数据了，读出来的data长度为0，len(data)==0
        while len(data) > 0:
            print(num)
            data = sock.recv(1024)
            num += len(data)
            total_data += data
        with open("11.png", "wb") as f:
            f.write(total_data)

        #
        picfilename =os.getcwd()+"/11.png"   # tkinter.filedialog.askopenfilename(initialdir=os.getcwd())
        imageRGB = cv2.imread(picfilename)


        BPHlast,size_w_h ,mylocation_str, x, y, z = demo.main("normal", imageRGB,"nodialog")
        myall = "" + str(BPHlast)+"|"+size_w_h+"|"+ mylocation_str+"|" +x+"|" +y  +"|" +z
        print(myall)
        sock.send(myall.encode())
       #q.put(myall)
        #

        x=False
        sock.close()
    #sock.close()
    print("okokokoo")
    #return myall


if __name__ == "__main__":
    #############################
    #q=queue.Queue(3)


    # socket
    ##def socket_service():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 防止socket server重启后端口被占用（socket.error: [Errno 98] Address already in use）
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('0.0.0.0', 9990))  # '27.50.142.143'     '127.0.0.1'
        chunks = []
        s.listen(10)
    except socket.error as msg:
        print(msg)
        sys.exit(1)
    print('Waiting connection...')
    xx = True
    while xx:
        conn, addr = s.accept()
        t = threading.Thread(target=deal_data, args=(conn, addr))
        t.start()
        #xx = False

    #################### #  end  socket
